<?php
/**
 *  Copyright (c) 2013, advert-m102
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *   1. Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *   2. Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *   3. All advertising materials mentioning features or use of this software
 *      must display the following acknowledgement:
 *      This product includes software developed by the dsphinx.
 *   4. Neither the name of the dsphinx nor the
 *      names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY dsphinx ''AS IS'' AND ANY
 *  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED. IN NO EVENT SHALL dsphinx BE LIABLE FOR ANY
 *  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 */

DEFINE ("__AJAX", TRUE);

require_once ('../Library/Ajax/Ajax.php');
require_once ('../Library/Timer.php');

$_return = NULL;
$param   = array();
$db      = new MyDB();
$queryies = array();


if ($results = file_get_contents("php://input")) {

    $results = $_POST; // POST faster for simple calls
    $_tmp    = urldecode(($results['data']));
    $param   = unserialize(($_tmp));
    $page_show   = $results['page'] ? (urldecode(($results['page']))-1) : 0;

}

  //  trigger_error("page ".$page_show);

$timer = ExecTimer::Start();

//   SQL Here
//
   require_once ('../Library/Sessions/Sessions.php');

include('../../Private/admin_advert/auth_db.php');
$category  = $param['category'];
$query     = $param['query'];
$action_id = $param['action_id'];
$sql_f1    = 'SELECT field_search.id as fcai, field_search.field_id as fcafi, category_action.id as cai, field_search.category_action_id as fcacai,
 field_search.ordering as fcao, field.name as fn, field.id as fi, category.name as cn, field.parameters as fpara FROM field_search, category_action,
  field, category WHERE field_search.field_id = field.id AND field_search.category_action_id=category_action.id AND category_action.category_id=category.id
   AND category.id=' . $category . ' ORDER BY field_search.ordering';
$result_f1 = mysqli_query($con, $sql_f1);
$sql_yo1 = 'SELECT * FROM field_category_action JOIN category_action WHERE field_category_action.category_action_id = category_action.id AND category_action.category_id='.$category.' ORDER BY field_category_action.ordering';

if (empty($category))
{
   $sql_yo1 = 'SELECT * FROM field_category_action JOIN category_action JOIN field WHERE field_category_action.category_action_id = category_action.id  OR upper(field.name) LIKE \'%'.strtoupper($query).'%\' ORDER BY field_category_action.ordering';
    //$sql_yo1 = 'SELECT * FROM field';
}
$result_yo1 = mysqli_query($con, $sql_yo1);
//echo $sql_yo1;
//return;
/*while ($row_f1 = mysqli_fetch_array($result_f1)) {
    $var = 'var' . $row_f1['fcafi'];
    if (!empty($param[$var])) {
        $sql_t1 = $sql_t1 . ' AND field_data.' . $var . '=' . $param[$var];
    }
}
//echo $sql_t1.'<br';
if (!empty($category)) {
    $sql_t1 = $sql_t1 . ' AND category_action.category_id =' . $category;
}
if (!empty($query)) {
   // $sql_t1 = $sql_t1 . ' AND field_data.var LIKE %' . $query . '%';
}
if (!empty($action_id)) {
    $sql_t1 = $sql_t1 . ' AND field_data.action_id=' . $action_id;
}*/
$var_name = "";
$var_query =" AND ( ";
while ($row_yo1 = mysqli_fetch_array($result_yo1))
{
    $var = 'var'.$row_yo1['field_id'];
    $var_name = $row_yo1['name'];
    if (!empty($var_name))
    {

    }
    $sql_yo2 = 'SELECT * FROM field WHERE field.id='.$row_yo1['field_id'].' LIMIT 1';
    $result_yo2 = mysqli_query($con, $sql_yo2);
    $row_yo2 =  mysqli_fetch_array($result_yo2);
    if ($row_yo2['parameters'] == "TEXT" OR $row_yo2['parameters'] == "TEXTAREA")
    {
        $queryies[] =  '%'.strtoupper($query).'%';
        //print_r($queryies);
        $var_query = $var_query.' upper(field_data.'.$var.') LIKE ? OR ';
        // $queryies[] =  '33';

    }

}
$var_query = $var_query.' 1=0 )';
$sql_t1    = "";
while($row_f1 = mysqli_fetch_array($result_f1))
{
    $var = 'var'.$row_f1['fcafi'];
    if (!empty($param[$var]))
    {
        $sql_t1 = $sql_t1.' AND field_data.'.$var.'='.$param[$var];
    }
}

//echo $sql_t1.'<br';


if (!empty($action_id))
{
    $sql_t1 = $sql_t1.' AND field_data.action_id='.$action_id;
}
if (!empty($query))
{
    $sql_t1 = $sql_t1.$var_query;
}

if (!empty($category))
{
    $sql_t1 = $sql_t1.' AND category_action.category_id ='.$category;
}
else
{
    $sql_final = '';
}

    $sql_final = "select count(*) as total  FROM field_data";
    $tmp = $db->sql($sql_final);
    $_total = $tmp[0]['total'];


    $page_show = (int) $page_show;
    $start = $page_show * 25;
    $end = $start + 25;


// $img= "var45";
//$sql_final = 'SELECT field_data.*,'.$img.' as IMAGE  FROM field_data join field_category_action join category_action WHERE
$sql_final = 'SELECT field_data.*  FROM field_data join field_category_action join category_action WHERE
                        field_data.field_category_action_id = field_category_action.id AND
                        field_category_action.category_action_id = category_action.id ' . $sql_t1 . " LIMIT $start, $end";


$sql_final_pagination = 'SELECT count(*) as total  FROM field_data join field_category_action join category_action WHERE
                        field_data.field_category_action_id = field_category_action.id AND
                        field_category_action.category_action_id = category_action.id ' . $sql_t1  ;
$rec = $db->rawQuery($sql_final_pagination,$queryies);
$pages_all = $rec[0]['total'];
$pages = $pages_all /  25;
$pages = ceil($pages);


// $sql_final = "SELECT * from Auth";

// echo $sql_final;
//return;
//$sql_final = "SELECT field_data.* FROM field_data join field_category_action join category_action WHERE field_data.field_category_action_id = field_category_action.id AND field_category_action.category_action_id = category_action.id AND field_data.var47=33 AND category_action.category_id =11 LIMIT 0, 30 ";;
$rec = $db->rawQuery($sql_final,$queryies);
//$rec = $db->sql($sql_final);
$cx = count($rec);


if ($cx == 0) {

    echo '<div> <small>Βρέθηκαν ' . $pages_all . ' αγγελίες </small> <div class="alert alert-error" style="width:85%;"> Δεν βρέθηκαν αποτελέσματα </div></div>';

    return $_return;
}

echo '<div> <small>Βρέθηκαν ' . $pages_all . ' αγγελίες απο σύνολο '.$_total.' </small></div>';


foreach ($rec as $t) {

     //   print_r($t);
    $id    = $t['id'];
    $title = $t['var44'];

    $title   = '<a href="?page=search&query_id=' . $id . '">' . $title . '</a>';
    $img     =  '<img src="data:image/jpeg;base64,' . base64_encode( $t['var54'] ) . ' " />';
    $keimeno = $t['var45'];
    $price   = $t['cx'];


    echo '
        <div class="results_lines" style="width:85%;">
               <div class="results_lines_img"  style="padding: 10px 10px 10px 0px;"> ' . $img . '</div>
               <div class="results_lines_title">' . $title . ' </div>
               <div class="results_lines_text"> ' . $keimeno . ' </div>
               <div class="results_lines_bottom">' . $price . ' </div>
        </div>
        ';


}


echo '<div style="clear:both;"></div>';



 if ($pages >1 ) {

      //  echo " $pages_all   pages = $pages  , showing $page_show , st $start to $end";
echo '<div class="pagination">
  <ul>


';

     if ($page_show>1)
         echo '<li><a onclick="gopage('.($page_show-2).');" sshref="?page=search&pg='.$i.'"> Prev </a> </li>';


     for ($i=0;$i<=$pages;$i++) {

        if ($i>15 )
             break;

         $cl = ($page_show == $i) ?' class="active" ' : NULL;


       echo '<li '.$cl.'><a onclick="gopage('.$i.');"  sshref="?page=search&pg='.$i.'"> '.($i+1).' </a> </li>';
     }

     if ($page_show< $pages)
          echo '<li><a onclick="gopage('.($page_show+2).');"  > Next </a> </li>';

     echo '  </ul>
</div>';

  }


//foreach ($param as $x => $y) {
//    echo "<strong> " . $x . " </strong> $y <br />";
//}


$strenc = $results['data'];


echo '<div> <small> Χρόνος Αναζήτησης : ' . ExecTimer::theTime() . ' δευτερόλεπτα </small></div>';
?>



  <script>

    function gopage(page) {
     //   alert('ok' + page);
    $( document ).ready(function() {

        $("#results").html('<br/>   <img src="Media/images/loading2.gif" style="margin:auto; display:block;">       <br/>');

        $("#results").load("App/Ajax/search_query.php", { data : '<?php echo $strenc;?>', page : page  }, function (data) {
            //       alert( "Load was performed." +data );
        });

     });
    }

   </script>
